package com.example.demoapp.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.airbnb.lottie.L;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.demoapp.R;
import com.example.demoapp.bean.Res;
import com.example.demoapp.bean.User;
import com.example.demoapp.bean.util.JSONParser;
import com.example.demoapp.config.URLs;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class StartAnimationActivity extends AppCompatActivity {
    private Context mContext;
    private StartAnimationActivity main;
    private SharedPreferences  sharedPreferences;
    private int displayCount;
    private int requestCount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_animation);
        displayCount=0;
        requestCount = 0;
        mContext = this;
        main=this;
        LottieAnimationView animationView = findViewById(R.id.animation_view);
        animationView.setAnimation(R.raw.animation);
        // 设置请求队列结束监听
        RequestQueue.RequestFinishedListener<Object> finishLinstener = new RequestQueue.RequestFinishedListener<Object>() {
            @Override
            public void onRequestFinished(Request<Object> request) {
                requestCount++;
            }
        };
        // 动画事件监听
        animationView.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                // 动画开始时的逻辑
                startLogin();
                getTabname();
            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {
                // 动画被取消时的逻辑
                //取消监听
                MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().removeRequestFinishedListener(finishLinstener);
                SharedPreferences preferences = mContext.getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
                Intent activity = new Intent();
                if(preferences.contains("username")){
                    activity.setClass(mContext, MainActivity.class);
                }else {
                    activity.setClass(mContext, LoginActivity.class);
                }
                startActivity(activity);
                finish();
            }

            @Override
            public void onAnimationRepeat(Animator animator) {
                // 动画重复播放时的逻辑
                displayCount++;
                Log.i("播放了",String.valueOf(displayCount));
                if (requestCount >= 4) {
                    animationView.cancelAnimation();
                }
            }

        });
        MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().addRequestFinishedListener(finishLinstener);
        animationView.setRepeatCount(LottieDrawable.INFINITE); // 设置循环播放


        animationView.playAnimation();
    }


    private void startLogin(){
        sharedPreferences = mContext.getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
        if(sharedPreferences.contains("username")){
            String username = sharedPreferences.getString("username","");
            String password = sharedPreferences.getString("password","");
            Map map=new HashMap();
            // 输入参数
            map.put("userName", username);//Admin
            map.put("password", password);//123
            //直接登录，更新token
            MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.Login, new JSONObject(map),
                    new Response.Listener() {
                        @Override
                        public void onResponse(Object response) {
                            Res res = JSONParser.parseJson(response.toString());
                            if (res.isSuccess()){
                                Log.d("login_response",res.toString());
                                // 保存用户信息
                                User user = JSONParser.parseUserJson(res.getData().toString());
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("username", username);
                                editor.putString("password", password);
                                editor.putString("user",new Gson().toJson(user));
                                editor.putString("token",user.getToken());
                                editor.apply();
                                Toast.makeText(mContext, "欢迎你， "+user.getNickName(), Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(mContext, "系统出错，请联系后台管理员", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mContext, "网络出错，请联系管理员", Toast.LENGTH_SHORT).show();
                }
            }));
        }
    }
    private void getTabname(){
        String[] tabs = new String[]{"sys_tab_doc","sys_tab_video","sys_tab_news","sys_tab_audio"};
        Arrays.stream(tabs).forEach(tab -> {
            MySingleton.getInstance(mContext.getApplicationContext())
                    .getRequestQueue()
                    .add(request(Arrays.asList(tabs).indexOf(tab), tab));
        });
    }

    private JsonObjectRequest request(int index,String type){
        Map map = new HashMap();

        map.put("dictType",type);
        map.put("page","1");
        map.put("pageSize","10000");
        map.put("status","");
        return new JsonObjectRequest(URLs.getsysDictData, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            ArrayList<String> tabName = new ArrayList<String>();
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                JSONArray dataArray = jdata.getJSONArray("records");
                                // 遍历JSONArray并解析每个对象
                                for (int i = 0; i < dataArray.length(); i++) {
                                    JSONObject dataObject = dataArray.getJSONObject(i);
                                    tabName.add(dataObject.getString("dictLabel"));
                                }
                                switch (index){
                                    case 0:
                                        URLs.art_tabName = tabName.toArray(new String[tabName.size()]);
                                        break;
                                    case 1:
                                        URLs.video_tabName = tabName.toArray(new String[tabName.size()]);
                                        break;
                                    case 2:
                                        URLs.info_tabName = tabName.toArray(new String[tabName.size()]);
                                        break;
                                    case 3:
                                        URLs.audio_tabName = tabName.toArray(new String[tabName.size()]);
                                        break;
                                }
                            }
                        } catch (Exception e) {
                            Log.i("获取字典错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
                Log.i("网络出错",error.toString());
            }
        });
    }
}